<?php
/**
 * 用户发布车辆管理
 * Created by PhpStorm.
 * User: andy
 * Date: 2019/11/21
 * Time: 下午6:34
 */

namespace app\control\controller;

use app\common\model\CarLicenseModel;
use app\common\model\CarLicenseMoreModel;
use app\common\model\MemberModel;
use app\common\model\SystemMsgModel;
use app\common\model\UserCarMessageModel;
use app\common\model\UserCarModel;
use app\common\model\CarBrandModel;
use app\common\model\CarModel;
use app\common\model\CarSeriesModel;
use app\common\model\UserRecordModel;
use think\facade\Request;

class UserCarController extends AdminBaseController
{
    /**
     * 已发布列表
     */
    public function index(UserCarModel $uc){
        $data=Request::param("");
        $where=$this->search($data);

        $list=$uc->getALL($where);

        $this->assign("list",$list);
        $this->assign("gd",$data);
        return $this->fetch();
    }

    /**
     * 审核发布列表
     */
    public function shcar(UserCarModel $uc){
        $data=Request::param("");
        $where=$this->search($data);

        $list=$uc->getWaitCar($where);

        $this->assign("list",$list);
        $this->assign("gd",$data);
        return $this->fetch();
    }

    /**
     * @param $id
     * @param UserCarModel $uc
     * @return mixed
     */
    public function detail($id,UserCarModel $uc){
        $info=$uc::get($id);

        $brand=CarBrandModel::field("brand")->where('brand_id',$info->brand_id)->find();
        $series=CarSeriesModel::field('series_name')->where('series_id',$info->series_id)->find();
        $car=CarModel::field('car_name,series_max,car_case')->where('car_id',$info->car_id)->find();

        $info->brand_name=$brand->brand;
        $info->series_name=$series->series_name;

        $info->car_name="";
        $info->series_max="";
        $info->car_case="";
        $info->vin_url="";
        if(!empty($car)){
            $info->car_name=$car->car_name;
            $info->series_max=$car->series_max;
            $info->car_case=$car->car_case;
        }


        if(empty($info->img_list)){
            $info->img_list=[];
        }else{
            $info->img_list=json_decode($info->img_list,true);
        }

        $vin=CarLicenseModel::where('vin','=',$info['vin'])->find();
        if(!empty($vin)) $info->vin_url=$vin->vin_url;

        $this->assign('info',$info);
        return $this->fetch();
    }

    /**
     * 搜索
     * @return array
     */
    private function search($data){

        $where=[];

//        if(!empty($data["title"])){
//            $where[]=["title",'like',"%{$data['title']}%"];
//        }

        if(!empty($data["cat_id"])){
            $where[]=["cat_id","=",$data["cat_id"]];
        }

        if (!empty($data["status"]) && $data["status"] != -2) {
            $where[] = ["status", '=', $data['status'] - 1];
        }

        if (!empty($data["mobile"])) {
            $u = MemberModel::where('mobile', $data["mobile"])
                ->field('uid')
                ->find();

            $where[] = ["user_id", '=', $u['uid']];
        }

        if (!empty($data["number"])) {
            $where[] = ["car_number", '=', $data['number']];
        }

        return $where;
    }

    /**
     * 删除
     */
    public function del(UserCarModel $m)
    {
        $id = Request::post("id");
        $type = Request::post("type");

        if(empty($type)){
            $status = $m->del($id);
            if ($status['status']) {
                $this->success($status['msg']);
            } else {
                $this->error($status['msg']);
            }

        }else{
            $error = 0;
            $sussuc = 0;
            foreach ($id as $vo) {
                $status = $m->del($vo);
                if (!$status['status']) {
                    $error++;
                    continue;
                } else {
                    $sussuc++;
                }
            }

            $this->success("成功删除{$sussuc}条，删除失败{$error}条");
        }

    }

    /**
     * 状态修改
     */
    public function acStatus(){
        $id=Request::post("id");
        $status=Request::post("status");
        $content=Request::post("content");

        $am=UserCarModel::get($id);
        $am->status=$status;

        if($status==1){
            $am->publish_time=time();
        }

        $st=$am->save();

        if($st){
            if($status==1){
                //获得佣金
                MemberModel::pushGold($am["user_id"], 0,$id);

/*                $giveMoney=getSystem("get_money")?getSystem("get_money"):0;

                if(!empty($am->invite_code)){

                    $user_id=deInviteCode($am->invite_code);

                    $user=MemberModel::get($user_id);

                    if(!empty($user) && $am->user_id!=$user_id){

                        $status=MemberModel::where('uid',$user_id)->setInc("distribut_money",$giveMoney);

                        if($status){
                            $ur=new UserRecordModel();
                            $data=[
                                "user_id"=>$user_id,
                                "status"=>UserRecordModel::SHOW_STATUS,
                                "money"=>$giveMoney,
                                "now_balance"=>$user->distribut_money+$giveMoney,
                            ];
                            $ur->adds($data);
                        }

                    }
                }*/
            }

            if($status==2){
                MemberModel::subGold($id,0);

                if(!empty($content)){
                    $sysData=[
                        'send_user_id'=>$am["user_id"],
                        'title'=>'[系统消息]您发布的车辆已经驳回',
                        'user_car_id'=>$id,
                        'content'=>$content,
                        'create_time'=>time(),
                        'status'=>1,
                    ];
                    SystemMsgModel::adds($sysData);
                }
            }

            $this->success("操作成功！");
        }else{
            $this->error("操作失败！");
        }
    }

    /**
     * 数据导出
     * @return bool
     * @throws \PhpOffice\PhpSpreadsheet\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
   public function _export(){
       $name='用户发布车辆';
       $tit=[
           'ID',
           '发布用户',
           '汽车品牌',
           '汽车系列',
           '汽车型',
           '汽车指导价',
           '变速箱',
           '汽车颜色',
           '上牌时间',
           '行驶里程',
           '售价',
           '交强险到期时间',
           '年检到期时间',
           '牌照归属地',
           '过户次数',
           '有无抵押',
           '车辆性质',
           '排放标准',
           '看车地点',
           '加装配置',
           '联系人',
           '联系电话',
           '发布时间',
           '状态',
           '销售状态',
           '车况描述',
       ];

       $param = Request::param("");
       $where = $this->search($param);

       if(empty($param['type'])){
           $where[]=['status','in',[UserCarModel::HIDE_STATUS,UserCarModel::NO_STATUS]];
       }else{
           $where[]=['status','=',UserCarModel::SHOW_STATUS];
       }
       $arr=UserCarModel::getSelect($where);

       if(!count($arr)){
           $this->error("没有数据！");
           return false;
       }

       $data=[];
       foreach ($arr as $key=>$info){
           $data[$key]['ID']=$info['id'];
           $data[$key]['mobile']=$info['user']['mobile'];
           $data[$key]['brand_name']=$info['brand_name'];
           $data[$key]['series_name']=$info['series_name'];
           $data[$key]['car_name']=$info['car_name'];
           $data[$key]['series_max']=$info['series_max'];
           $data[$key]['car_case']=$info['car_case'];
           $data[$key]['car_color']=$info['car_color'];
           $data[$key]['card_time']=date('Y-m',$info['card_time']);
           $data[$key]['mileage']=$info['mileage'].'万公里';
           $data[$key]['price']=$info['price'];
           $data[$key]['strong_time']=date('Y-m',$info['strong_time']);
           $data[$key]['yearly_time']=date('Y-m',$info['yearly_time']);

           $data[$key]['card_come']=$info['card_come'];
           $data[$key]['transfer_times']=$info['transfer_times'].'次';
           $data[$key]['pledge']=$info['pledge'];
           $data[$key]['nature']=$info['nature'];
           $data[$key]['standard']=$info['standard'];

           $data[$key]['address']=$info['address'];
           $data[$key]['add_conf']=$info['add_conf'];
           $data[$key]['real_name']=$info['real_name'];
           $data[$key]['real_mobile']=$info['mobile'];
           $data[$key]['create_time']=$info['create_time'];
           $data[$key]['status']=arrText($info['status'],[0=>'审核中',1=>'已通过',2=>'已拒绝']);
           $data[$key]['sell_status']=arrText($info['sell_status'],[-1=>'下架',0=>'未售',1=>'已售']);
           $data[$key]['content']=$info['content'];
       }
       exportExcel($name,$tit,$data);
   }

    /**
     * 评论列表
     * @param ArticleMessageModel $am
     * @return mixed
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function message(UserCarMessageModel $am){
        $data=Request::param("");
        $where=$this->search($data);

        $list=$am ->getALL($where);

        $this->assign("list",$list);
        $this->assign("gd",$data);
        return $this->fetch();
    }

    /**
     * 留言详情
     * @param $id
     * @return mixed
     */
    public function msg_detail($id,$t=0){
        $info=UserCarMessageModel::get($id);

        if(!empty($info)){
            $brand=CarBrandModel::field("brand")->where('brand_id',$info['car']['brand_id'])->find();
            $series=CarSeriesModel::field('series_name')->where('series_id',$info['car']['series_id'])->find();
            $u=MemberModel::field('mobile')->where('uid',$info['car']['user_id'])->find();

            $info->brand_name=$brand->brand;
            $info->series_name=$series->series_name;
            $info->fmobile=$u->mobile;
        }

        $this->assign('info',$info);
        $this->assign('t',$t);
        return $this->fetch();
    }

    /**
     * 审核评论
     */
    public function msg_status(){
        $id=Request::post("id");
        $status=Request::post("status");
        $content=Request::post("content");

        $sta=UserCarMessageModel::get($id);
        $sta->status=$status;
        $st=$sta->save();

        if($st){

            if($status==-1){
                MemberModel::subGold($id,1);

                if(!empty($content)){
                    $sysData=[
                        'send_user_id'=>$sta["user_id"],
                        'title'=>'[系统消息]您发布的留言已经驳回',
                        'user_car_id'=>$sta["user_car_id"],
                        'content'=>$content,
                        'create_time'=>time(),
                        'status'=>1,
                    ];
                    SystemMsgModel::adds($sysData);
                }

            }

            $this->success("操作成功！");
        }else{
            $this->error("操作失败！");
        }
    }

    /**
     * 批量删除
     */
    public function msg_del_all(UserCarMessageModel $cat){
        $id=Request::post("ids");

        $error=0;
        $sussuc=0;
        foreach ($id as $vo){
            $status=$cat->del($vo);
            if(!$status['status']){
                $error++;
                continue;
            }else{
                $sussuc++;
            }
        }

        $this->success("成功删除{$sussuc}条，删除失败{$error}条");
    }

    /**
     * 锁定车源
     */
    public function lockCar(){
        $id=Request::post("id");

        $info=UserCarModel::find($id);

        $info->publish_time=time()+(3600*8);
        $status=$info->save();

        if ($status) {
            $this->success("成功锁定8小时！");
        } else {
            $this->error("锁定失败！");
        }
    }

    /**
     * 拒绝
     * @param $id
     * @return mixed
     */
    public function no_detail($id,$type=0){
        $this->assign("id",$id);
        $this->assign("type",$type);
        return $this->fetch();
    }
}